// pages/apNetwork/apNetwork.js
var util = require('../../utils/util.js')
const app = getApp();
var udp;
var udpDiscover;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    curWifi:'wifi名称',
    inputNewPwdValue:'',
    isIOS:false,
    apWifi:[],
    port:0,
    apGuangBo:'',
    wifiGuangBo:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 初始化 Wi-Fi 模块。
    var that=this;
    wx.getSystemInfo({
      success(res) {
        that.setData({
        isIOS: res.platform === 'ios'
        })
        if (that.data.isIOS) {
          wx.showModal({
            title: '提示',
            content: '由于系统限制，iOS用户请手动进入系统WiFi页面，然后返回小程序。',
            showCancel: false,
            success() {
              that.startWifi()
            }
          })
          return
        }
        that.startWifi();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    udp.close()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {


  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 获取输入密码
  bindNewPwdInput: function (e) {
    this.setData({
      inputNewPwdValue: e.detail.value
    })
  },
  // 初始化wifi
  startWifi() {
    var that = this;
    // 连接wifi
    wx.startWifi({
      success(res) {
        console.log(res.errMsg);
        wx.getConnectedWifi({
          success(res){
            // 获取当前连接wifi
            wx.getConnectedWifi({
              success(res) {
                console.log(res);
                that.setData({
                  curWifi: res.wifi.SSID,
                })
              },
              fail(err) {
                console.log(err);
              }
            })
            // 获取wifi列表函数
            // that.wifiListFun()
          },
          fail(res) {
            console.log(res);
          }
        })
      }
    })
  },
  // 获取wifi列表
  wifiListFun(){
    var that=this;
    wx.getWifiList({
      success: (res) => {
        console.log(res);
        wx.onGetWifiList((res) => {
          console.log(res);
          const wifiList = res.wifiList
          for (var i = 0; i < wifiList.length; i++) {
            var ssid = wifiList[i].SSID;
            if (ssid.indexOf("zcy_" + app.globalData.modeId) > -1) {
              that.data.apWifi.push(wifiList[i]);
            }
          }
        })
      },
      fail(err) {
        console.error(err);
      }
    })
  },
  // 连接热点发送完广播并收到回复后，开始连接路由器并发生设备发现
  sendDiscoverFun() {
    var that = this;
    udpDiscover = wx.createUDPSocket();
    var locationPort = udpDiscover.bind();
    console.log("当前端口 " + locationPort);
    clearInterval(that.data.wifiGuangBo);
    that.data.wifiGuangBo = setInterval(function () {
      var times = Date.parse(new Date()) / 1000;
      var parm = {
        "modelId": that.data.chanpinID,
        "platform": "0",
        "timestmp": times.toString()
      }
      udpDiscover.send({
        address: '255.255.255.255',
        port: 7682,
        message: JSON.stringify(parm)
      })
      console.log("send: " + JSON.stringify(parm))
    }, 1000)

    udpDiscover.onMessage(function (res) {
      clearInterval(that.data.wifiGuangBo);
      var mes = util.newAb2Str(res.message);
      console.log("recv: " + mes)
      var decDid = mes.deviceId;
      var timestamp = new Date().getTime();
      var param = {
        "did": decDid,
        'uid': app.globalData.openId,
        'gid': app.globalData.modeId
      }
      var params = JSON.stringify(param);
      wx.request({
        url: 'https://papi.zcyun.cn/v1/device/bind',
        method: "POST",
        data: {
          "did": decDid,
          'uid': app.globalData.openId,
          'gid': app.globalData.modeId
        },
        header: {
          'content-type': 'application/json', // 默认值
          'openId': app.globalData.openId,
          'ts': timestamp,
          'sign': util.sha1("POST" + '/v1/device/bind' + params + timestamp + app.globalData.openKey)
        },
        success(res) {
          console.log(JSON.stringify(res.data));

          if (res.data.code == 0) {
            console.log("11111111111");
            // 返回设备列表
            wx.switchTab({
              url: '../index/index'
            })
          }
        }
      })
    })
  },
  // 发送广播
  sendFun(){
    var that=this;
    var udpInter;
    if (wx.canIUse('createUDPSocket')) {
      console.log('good use')
    } else {
      const version = wx.getSystemInfoSync().SDKVersion
      console.log('bad use, version is ' + version)
      wx.showToast({
        title: '不支持UDP通信',
        icon: 'none'
      })
      return
    }
    udp = wx.createUDPSocket()
    const port = udp.bind()
    udp.onListening(function (res) {
      wx.showToast({
        title: "监听中" + that.data.curWifi,
        icon: 'none',
        duration: 2000
      })
    })
    clearInterval(that.data.apGuangBo);
    that.data.apGuangBo=setInterval(function(){
      var parms = {
        "ssid": that.data.curWifi,
        "pwd": that.data.inputNewPwdValue,
        "modelId": app.globalData.modeId,
        "platform": "0"
      }
      udp.send({
        address: '255.255.255.255',
        port: '7682',
        message: JSON.stringify(parms)
      })
    },1000)
    udp.onMessage(function (res) {
      clearInterval(that.data.apGuangBo);
      var recvMsg = util.newAb2Str(res.message);
      console.log("recv: " + recvMsg);
      if ((recvMsg.indexOf("{\"errCode\":\"0\"}") > -1) && that.data.iswifiGuangBo) {
        that.setData({
          iswifiGuangBo: false
        })
        wx.connectWifi({
          SSID: that.data.curWifi,
          password: that.data.inputNewPwdValue,
          success: function (res) {
            wx.showToast({
              title: "已连接至" + that.data.curWifi,
              icon: 'none',
              duration: 2000
            })
            that.sendDiscoverFun();
          },
          fail: function (err) {
            console.log(err);
          }
        })
      }
      else if (recvMsg.indexOf("{\"errCode\":\"1\"}") > -1) {
        wx.showToast({
          title: '型号不匹配！',
          icon: 'none'
        })
      }
    })
    wx.connectWifi({
      SSID: that.data.curWifi,
      password: that.data.inputNewPwdValue,
      success: function (res) {
        wx.showToast({
          title: "已连接至" + that.data.curWifi,
          icon: 'none',
          duration: 2000
        })
        clearInterval(that.data.wifiGuangBo);
        var timestamp = new Date().getTime();
        that.data.wifiGuangBo=setInterval(function(){
          var parm = {
            "modelId": app.globalData.modeId,
            "platform": "0",
            "timestmp": timestamp
          }
          udp.send({
            address: '255.255.255.255',
            port: '7682',
            message: JSON.stringify(parm)
          })
        },1000)

      },
      fail: function (err) {
        console.log(err);
      }
    })
  },
  // 开始配置
  startMatch:function(){
    var that=this;
    if(that.data.inputNewPwdValue.length==0){
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
    }else{
      wx.getWifiList({
        success: (res) => {
          console.log(res);
          wx.onGetWifiList((res) => {
            console.log(res);
            const wifiList = res.wifiList
            for (var i = 0; i < wifiList.length; i++) {
              var ssid = wifiList[i].SSID;
              if (ssid.indexOf("zcy_" + app.globalData.modeId) > -1) {
                that.data.apWifi.push(wifiList[i]);
              }
            }
            if (that.data.apWifi.length) {
              if (that.data.isIOS) {
                wx.setWifiList({
                  wifiList: [{
                    SSID: res.apWifi[0].SSID,
                    password: ''
                  }]
                })
              } else {
                wx.connectWifi({
                  SSID: that.data.apWifi[0].SSID,
                  password: '',
                  success: function (res) {
                    console.log("已连接至" + that.data.apWifi[0].SSID);
                    that.sendFun();
                  },
                  fail: function (err) {
                    console.log(err);
                  }
                })
              }
            } else {
              wx.showToast({
                title: '请确认设备是否进入ap模式',
                icon: 'none'
              })
            }
          })
        },
        fail(err) {
          console.error(err);
        }
      })

    }
  }
})